<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="query.billType" style="width: 170px; margin-right: 2px;">
          <el-option label="订单" value="1" />
          <el-option label="押金" value="8" />
        </el-select>
        <el-input v-model.trim="query.billCode" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="收支类型:" prop="inOutType">
        <el-select v-model="query.inOutType" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in inOutTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易渠道:" prop="fromPlat">
        <el-select v-model="query.fromPlat" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in fromPlatMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易方式:" prop="payType">
        <el-select v-model="query.payType" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in payTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易机构:" class="merge-item" :table-form-merge="1.5" prop="orgId">
        <el-tree-select
          v-model="query.orgId"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgId',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
        />
        <div style="width: 120px; padding-left: 20px;">
          <el-checkbox v-model="query.option" label="包含下级" />
        </div>
      </el-form-item>
      <el-form-item label="单据状态:" prop="billStatus">
        <el-select v-model="query.billStatus" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in billStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="交易类型:" prop="tradeType">
        <el-select v-model="query.tradeType" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in tradeTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" label="交易时间:">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[90702,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div class="btns">
      <el-button-group>
        <el-button v-permission="[90702,2]" type="primary" icon="el-icon-download" :loading="$loadingPlugin.exportFile" @click="exportFile">导出</el-button>
      </el-button-group>
      <div>
        押金收入：
        <el-popover
          placement="top"
          width="200"
          trigger="hover"
          popper-class="popper-style"
        >
          <div>线上押金收入：{{ statistics.onlineDepositIncome }}</div>
          <div>线下押金收入：{{ statistics.offlineDepositIncome }}</div>
          <span slot="reference" class="num">{{ statistics.depositIncome }}</span>
        </el-popover>
        订单收入：
        <el-popover
          placement="top"
          width="200"
          trigger="hover"
          popper-class="popper-style"
        >
          <div>线上订单收入：{{ statistics.onlineOrderIncome }}</div>
          <div>线下订单收入：{{ statistics.offlineOrderIncome }}</div>
          <span slot="reference" class="num">{{ statistics.orderIncome }}</span>
        </el-popover>
        数据说明
        <el-popover
          placement="left"
          width="310"
          trigger="hover"
        >
          <div>
            <div class="desc-title">数据生成时间：</div>
            <div>线上押金收款：收到线上押金金额生成数据</div>
            <div>线下押金收款：单据状态=已审核，生成数据</div>
            <div>线上订单收款：收到线上订单金额生成数据</div>
            <div>线下订单收款：状态=已完成，生成数据</div>
            <div class="desc-title">数量：</div>
            <div>押金：每笔押金单不同规格瓶数之和</div>
            <div>订单：每笔订单不同规格瓶数之和</div>
            <div class="desc-title">交易金额：</div>
            <div>押金：每笔押金单的收款金额/退款金额</div>
            <div>订单：每笔订单的收款金额/退款金额</div>
            <div><div class="title">交易渠道：</div>回执已回的交易渠道</div>
            <div><div class="title">交易方式：</div>回执已回的交易方式</div>
            <div><div class="title">交易时间：</div>回执已回的时间</div>
            <div><div class="title">交易机构：</div>回执已回的交易机构</div>
            <div><div class="title">交易时单据状态：</div>回执已回的单据状态</div>
            <div><div class="title">交易时回执状态：</div>回执已回的回执状态</div>
          </div>
          <i slot="reference" class="el-icon-question" />
        </el-popover>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      element-loading-text="加载中"
      :column="tableData.column"
      :data="tableData.data"
      highlight-current-row
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <order-detail ref="orderDetail" />
    <popups
      ref="popups"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :payment-method-list="paymentMethodList"
      :pay-status-list="payStatusList"
      :paymen-fil-list="paymenFilList"
      :customer-type="customerType"
    />
  </div>
</template>

<script>
  import { queryReceiptBillRecordList, queryReceiptBillRecordStatistics, queryExportReceiptBillRecord, queryExportDomain, queryMap } from '@/api'
  import moment from 'dayjs'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'

  export default {
    name: 'cashTransactions',
    components: {
      orderDetail: () => import('@/views/orderCenter/orderManage/components/OrderDetails.vue'),
      popups: () => import('@/views/customerCenter/depositManage/components/Popups.vue')
    },
    data() {
      return {
        exportDomain: '',
        treeData: [],
        date: [moment().startOf('day'), moment().endOf('day')],
        inOutTypeMap: [],
        fromPlatMap: [],
        payTypeMap: [],
        billStatusMap: [],
        billTypeMap: [],
        tradeTypeMap: [],
        calcTypeList: [],
        paymentMethodList: [],
        payStatusList: [],
        paymenFilList: [],
        customerType: [],
        query: {
          billType: '',
          billCode: '',
          inOutType: '',
          fromPlat: '',
          payType: '',
          orgId: '',
          option: false,
          billStatus: '',
          tradeType: ''
        },
        searchParams: {},
        statistics: {},
        tableData: {
          data: [],
          column: [
            {
              prop: 'receiptBillCode',
              label: '交易流水',
              width: 200,
              showOverflowTooltip: true
            },
            {
              prop: 'outTradeNo',
              label: '线上交易流水号',
              width: 220,
              showOverflowTooltip: true,
              render: (h, { row }) => <span>{ row.payType !== 1 ? row.outTradeNo : '' }</span>
            },
            {
              prop: 'uploadBillCode',
              label: '交易单据号',
              showOverflowTooltip: true,
              width: 220
            },
            {
              prop: 'tradeType',
              label: '交易类型',
              width: 100,
              render: (h, { row }) => <span>{ row.tradeType && formatColumnMap(this.tradeTypeMap, 'value', row.tradeType, 'desc') }</span>
            },
            {
              prop: 'billType',
              label: '单据类型',
              width: 100,
              render: (h, { row }) => <span>{ row.billType && formatColumnMap(this.billTypeMap, 'value', row.billType, 'desc') }</span>
            },
            {
              prop: 'billCode',
              label: '业务单号',
              render: (h, { row }) => row.billType === 1 || row.billType === 8 ? <el-link underline={false} onClick={() => this.openDetail(row)}>{row.billCode}</el-link> : <span>{row.billCode}</span>
            },
            {
              prop: 'inOutType',
              label: '收支类型',
              width: 90,
              render: (h, { row }) => <span>{ row.inOutType && formatColumnMap(this.inOutTypeMap, 'value', row.inOutType, 'desc') }</span>
            },
            {
              prop: 'goodsCount',
              label: '商品数量',
              width: 90
            },
            {
              prop: 'cashFee',
              width: 100,
              align: 'right',
              label: '交易金额'
            },
            {
              prop: 'fromPlat',
              label: '交易渠道',
              width: 100,
              render: (h, { row }) => <span>{ row.fromPlat && formatColumnMap(this.fromPlatMap, 'value', row.fromPlat, 'desc') }</span>
            },
            {
              prop: 'payType',
              label: '交易方式',
              width: 100,
              render: (h, { row }) => <span>{ row.payType && formatColumnMap(this.payTypeMap, 'value', row.payType, 'desc') }</span>
            },
            {
              prop: 'payTime',
              label: '交易时间',
              width: 160,
              render: (h, { row }) => <span>{ row.payTime && parseTime(row.payTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
            },
            {
              prop: 'orgName',
              label: '交易机构',
              showOverflowTooltip: true
            },
            {
              prop: 'billStatus',
              label: '交易单据状态',
              width: 120,
              render: (h, { row }) => <span>{ row.billStatus && formatColumnMap(this.billStatusMap, 'value', row.billStatus, 'desc') }</span>
            }
          ]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList'
      ])
    },
    async created() {
      await Promise.all([this.getTreeData(), this.queryOptionsMap()])
    },
    methods: {
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.payTimeStart = moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss')
          query.payTimeEnd = moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss')
        }
        if (query.orgId) {
          const orgInfo = this.orgList.find(item => item.orgId === query.orgId)
          query.orgName = orgInfo.orgName
          if (query.option) {
            query.orgSNNo = orgInfo.orgSNNo
            delete query.orgId
          }
        }
        delete query.option
        const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
        if (diff > 365) {
          this.$message.error('交易时间最大支持查询1年')
          return
        }
        const res = await queryReceiptBillRecordList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        const params = { ...query }
        const res1 = await queryReceiptBillRecordStatistics(params)
        if (res1.data) this.statistics = res1.data
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3, res4, res5, res6] = await Promise.all([
          queryMap({ enumName: 'CashBillSource' }),
          queryMap({ enumName: 'PaymentMethod' }),
          queryMap({ enumName: 'CashBillStatus' }),
          queryMap({ enumName: 'Ord_BillType' }),
          queryMap({ enumName: 'TradeType' }),
          queryMap({ enumName: 'InOutType' })
        ])
        this.fromPlatMap = res1.data // 交易渠道
        this.payTypeMap = res2.data.filter(item => item.value === 1 || item.value === 1024) // 交易方式
        this.billStatusMap = res3.data.filter(item => item.value < 5) // 单据状态
        this.billTypeMap = res4.data // 单据类型
        this.tradeTypeMap = res5.data.filter(item => item.value < 3) // 交易类型
        this.inOutTypeMap = res6.data // 收支类型
      },
      // 查询押金单枚举
      async queryOptionsMapForDeposit() {
        const [res2, res3, res4, res5] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' }),
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'PayStatus' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' })])
        this.calcTypeList = res2.data.filter((item) => item.value !== 0) // 收款方式
        this.paymentMethodList = res3.data // 支付方式
        this.payStatusList = res4.data // 支付状态
        this.customerType = res5.data // 客户类型
        // 过滤支付方式
        const arr = ['现金', '微信支付', '支付宝', '银行支付']
        this.paymentMethodList.filter(item => {
          if (arr.includes(item.desc)) {
            this.paymenFilList.push(item)
          }
        })
      },
      async openDetail(row) {
        if (row.billType === 1) {
          await this.$refs.orderDetail.open({ orderCode: row.billCode })
        }
        if (row.billType === 8) {
          await this.queryOptionsMapForDeposit()
          await this.$refs.popups.open({ depositCode: row.billCode, depositId: 0, depStatus: 0 })
        }
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      async exportFile() {
        await this.getExportDomain()
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.tableData.column))
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryExportReceiptBillRecord({
            paramInfo: this.searchParams,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      reset() {
        this.date = []
        this.query = {
          billType: '',
          billCode: '',
          inOutType: '',
          fromPlat: '',
          payType: '',
          orgId: '',
          option: false,
          billStatus: '',
          tradeType: ''
        }
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
.svg-row {
  text-align: center;
  .svg-container {
    display: inline-block;
    width: 25px;
    cursor: pointer;
    .transfer-icon {
      width: 25px;
      height: 25px;
      vertical-align: middle;
    }
  }
}
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.btns {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #333;
  .num {
    margin-right: 10px;
    color: #02A7F0;
  }
}
.desc-title {
  margin-bottom: 5px;
  font-weight: 600;
}
.title {
  display: inline-block;
  margin-bottom: 5px;
  font-weight: 600;
}
</style>
